package com.iflytek.springboot_medicine.controller;

import com.iflytek.springboot_medicine.entity.Order;
import com.iflytek.springboot_medicine.entity.OrderItem;
import com.iflytek.springboot_medicine.pojo.ResponseMessage;
import com.iflytek.springboot_medicine.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/orders")
@CrossOrigin(origins = "*")
public class OrderController {
    @Autowired
    private OrderService orderService;
    
    @PostMapping
    public ResponseMessage<?> createOrder(@RequestBody Map<String, Object> request) {
        try {
            Order order = new Order();
            order.setUserName((String) request.get("userName"));
            order.setShippingAddress((String) request.get("shippingAddress"));
            order.setDeliveryName((String) request.get("deliveryName"));
            order.setDeliveryPhone((String) request.get("deliveryPhone"));
            order.setDeliveryAddress((String) request.get("deliveryAddress"));
            order.setPaymentMethod((String) request.get("paymentMethod"));
            order.setTotalAmount(Double.parseDouble(request.get("totalAmount").toString()));
            order.setRemark((String) request.get("remark"));
            
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> items = (List<Map<String, Object>>) request.get("items");
            List<OrderItem> orderItems = items.stream().map(item -> {
                OrderItem orderItem = new OrderItem();
                Object medicineId = item.get("medicineId");
                if (medicineId instanceof Long) {
                    orderItem.setMedicineId(((Long) medicineId).intValue());
                } else if (medicineId instanceof Integer) {
                    orderItem.setMedicineId((Integer) medicineId);
                } else {
                    orderItem.setMedicineId(Integer.parseInt(medicineId.toString()));
                }
                orderItem.setMedicineName((String) item.get("medicineName"));
                orderItem.setQuantity(Integer.parseInt(item.get("quantity").toString()));
                orderItem.setPrice(Double.parseDouble(item.get("price").toString()));
                orderItem.setSubtotal(Double.parseDouble(item.get("subtotal").toString()));
                return orderItem;
            }).toList();
            
            Order savedOrder = orderService.createOrder(order, orderItems);
            return ResponseMessage.success(savedOrder);
        } catch (Exception e) {
            return ResponseMessage.error("创建订单失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/user/{userName}")
    public ResponseEntity<?> getOrdersByUserName(@PathVariable String userName) {
        try {
            List<Order> orders = orderService.getOrdersByUserName(userName);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取订单失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/status/{status}")
    public ResponseEntity<?> getOrdersByStatus(@PathVariable Integer status) {
        try {
            List<Order> orders = orderService.getOrdersByStatus(status);
            return ResponseEntity.ok(orders);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取订单失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/items/{orderId}")
    public ResponseEntity<?> getOrderItems(@PathVariable Long orderId) {
        try {
            List<OrderItem> items = orderService.getOrderItems(orderId);
            return ResponseEntity.ok(items);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取订单项失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{orderId}/status/{status}")
    public ResponseEntity<?> updateOrderStatus(
            @PathVariable Long orderId,
            @PathVariable Integer status) {
        try {
            orderService.updateOrderStatus(orderId, status);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新订单状态失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{orderId}")
    public ResponseEntity<?> deleteOrder(@PathVariable Long orderId) {
        try {
            orderService.deleteOrder(orderId);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除订单失败: " + e.getMessage());
        }
    }
}
